package com.fuda.trade

import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.os.PersistableBundle
import android.provider.Settings
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentContainerView
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView


// subscribe new data from TradeAccessibilityService
// Approve new data and send back to TradeAccessibilityService for further processing
class MainActivity : AppCompatActivity()  {
    companion object
    {
        val TAG: String = MainActivity::class.java.simpleName
    }
    private lateinit var navController: NavController
    private lateinit var bottomNavigationView: BottomNavigationView
    private lateinit var fragmentContainerView: FragmentContainerView


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Find the BottomNavigationView and FragmentContainerView
        bottomNavigationView = findViewById(R.id.nav_view)
        fragmentContainerView = findViewById(R.id.nav_host_fragment_activity_main)

        // Initialize the NavController
        navController = (supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) as NavHostFragment).navController

        // Set up the AppBarConfiguration for the BottomNavigationView
        // val appBarConfiguration = AppBarConfiguration(setOf(R.id.navigation_strategies, R.id.navigation_orders, R.id.navigation_holdings))
        // setupActionBarWithNavController(navController, appBarConfiguration)

        // Set up the BottomNavigationView with the NavController
        bottomNavigationView.setupWithNavController(navController)


        // Check if the service is enabled
        if (!isAccessibilityServiceEnabled()) {
            // Prompt the user to enable the service
            promptEnableAccessibilityService()
        }

        // Show the appropriate dialog based on the data
        handleStartReason(intent)

    }

    override fun onPostCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onPostCreate(savedInstanceState, persistentState)

        // Usage:
        // val ipAddressService = IPAddressService(this) // Replace `this` with your activity or fragment context
        // ipAddressService.startListening()

    }

    override fun onResume() {
        super.onResume()
        // Check if the service is enabled
        if (!isAccessibilityServiceEnabled()) {
            // Prompt the user to enable the service
            promptEnableAccessibilityService()
        }
    }

    private fun isAccessibilityServiceEnabled(): Boolean {
        val serviceComponentName = ComponentName(this, TradeAccessibilityService::class.java)
        val settings = Settings.Secure.getString(contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES)
        return settings?.contains(serviceComponentName.flattenToString()) == true
    }

    private fun promptEnableAccessibilityService() {
        val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
        startActivity(intent)
    }

    private fun handleStartReason(intent: Intent) {

        // Retrieve data from the Intent
        val reason = intent.getStringExtra("START_REASON")
        val payload = intent.getStringExtra("PAYLOAD")
        when (reason) {
            "SERVER_HEARTBEAT_TIMEOUT" -> showDialogServerHeartbeat()
            "ASK_CONFIRM_MANUAL_TRADE_ORDER" -> payload?.let { showDialogConfirmTradeOrder(it) }
            else -> {
                // Default behavior if no matching data is found
                Log.d(TAG, "Ignore unknown reason: $reason")
                // Navigate to the default OrdersFragment
                navController.navigate(R.id.navigation_orders)
            }
        }
    }

    private fun showDialogServerHeartbeat() {
        val message ="The server heartbeat has not been received for ${TradeAccessibilityService.Companion.SERVER_HEARTBEAT_TIMEOUT_MS/1000} seconds. " +
                "Please check your internet connection and " +
                "restart 【富大助手】App to disable/enable 无障碍服务：富大助手辅助自动交易"

        // Create and show a dialog to inform the user about the missed heartbeat.
        val builder = AlertDialog.Builder(this)
        builder.setTitle("Server Heartbeat Missed ")
            .setMessage(message)
            .setPositiveButton("OK") { dialog, _ ->
                // Optionally, you can perform additional actions here, such as dismissing the dialog.
                finish()
            }

        val dialog = builder.create()
        dialog.show()
    }

    private fun showDialogConfirmTradeOrder(payload: String) {
        val message = "Please handle the payload: $payload"

        // Inflate the custom layout
        val inflater = layoutInflater
        val view = inflater.inflate(R.layout.dialog_confirm_trade_order, null)

        // Set the message text
        val textViewMessage: TextView = view.findViewById(R.id.textViewMessage)
        textViewMessage.text = message

        // Get the payload EditText
        val editTextPayload: EditText = view.findViewById(R.id.editTextPayload)
        editTextPayload.setText(payload)

        // Get the buttons
        val buttonOk: Button = view.findViewById(R.id.buttonOk)
        val buttonCancel: Button = view.findViewById(R.id.buttonCancel)

        // Set click listeners for the buttons
        buttonOk.setOnClickListener {
            // Optionally, you can perform additional actions here, such as dismissing the dialog.
            finish()
        }

        buttonCancel.setOnClickListener {
            // Optionally, you can perform additional actions here, such as dismissing the dialog.
            finish()
        }

        // Create and show the dialog
        val builder = AlertDialog.Builder(this)
        builder.setView(view)

        val dialog = builder.create()
        dialog.show()
    }

}

